/**
 * 最小化测试插件打包脚本
 * 用于诊断VSCode插件激活问题
 * 
 * @author lihengtt <lihengsir@gmail.com>
 * @github https://github.com/lihengtt
 */

const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

// 创建临时目录
const tempDir = path.join(__dirname, 'temp-minimal');
if (fs.existsSync(tempDir)) {
  fs.rmSync(tempDir, { recursive: true, force: true });
}
fs.mkdirSync(tempDir, { recursive: true });
fs.mkdirSync(path.join(tempDir, 'out'), { recursive: true });

// 复制必要文件
fs.copyFileSync(
  path.join(__dirname, 'package-minimal.json'),
  path.join(tempDir, 'package.json')
);

fs.copyFileSync(
  path.join(__dirname, 'out', 'extension-minimal.js'),
  path.join(tempDir, 'out', 'extension-minimal.js')
);

// 创建简单的图标文件
const iconDir = path.join(tempDir, 'resources');
fs.mkdirSync(iconDir, { recursive: true });

const svgContent = `<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  <path d="M12 2L2 7L12 12L22 7L12 2Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  <path d="M2 17L12 22L22 17" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  <path d="M2 12L12 17L22 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>`;

fs.writeFileSync(path.join(iconDir, 'cloud-upload.svg'), svgContent);

// 创建VSIX文件
console.log('开始打包最小化测试插件...');
try {
  process.chdir(tempDir);
  execSync('npx --yes vsce@1.75.0 package --no-yarn --no-dependencies');
  
  // 复制生成的VSIX文件到项目根目录
  const vsixFiles = fs.readdirSync(tempDir).filter(file => file.endsWith('.vsix'));
  if (vsixFiles.length > 0) {
    const vsixPath = path.join(tempDir, vsixFiles[0]);
    const targetPath = path.join(__dirname, 'vscode-rsync-deployment-test.vsix');
    fs.copyFileSync(vsixPath, targetPath);
    console.log(`打包成功: ${targetPath}`);
    console.log('安装命令: code --install-extension vscode-rsync-deployment-test.vsix');
  } else {
    console.error('打包失败: 未找到生成的VSIX文件');
  }
} catch (error) {
  console.error('打包失败:', error);
} finally {
  // 清理临时目录
  process.chdir(__dirname);
  fs.rmSync(tempDir, { recursive: true, force: true });
}